import React from 'react'
import { Breadcrumb, Popconfirm, Modal, Popover, Input, Form, message, Table, Button } from 'antd'
import $ from 'jquery'
import Config from '../../common/config'
import server from '../server'
import { hashHistory } from 'react-router'

const config = new Config()
const FormItem = Form.Item
const token = sessionStorage.getItem('token')
let UserInfo = sessionStorage.getItem('UserInfo')
UserInfo = UserInfo ? JSON.parse(UserInfo) : {}
const root = UserInfo.root
const auth = root ? {} : (UserInfo.auth ? (UserInfo.auth[server.serverName] || {}) : {})
class Roles extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rlTree: [],//角色树data
      selectedNumber: null,//选择的部门number
      selectedName: null,//选择的部门name
      visible: false,//模态框
      type: 0,//  编辑:1  新增:2
      // expandedRows: [],//展开的数据
    };
  }
  //获取部门树
  componentWillMount() {
    if (root || auth['/roles/tree']) {
      this.getRl().then(res => {
        if (res.code == 200) {
          console.log(res.rl)
          this.setState({
            rlTree: res.rl
          })
        } else if (res.code == 201) {
          message.info('获取数据失败')
        } else {
          message.info('服务器繁忙')
        }
      }).catch(err => {
        message.info('发生错误')
      })
    }
  }

  //获取部门树
  getRl() {
    return Promise.resolve(
      $.ajax({
        url: config.Priviliege + '/roles/tree',
        type: 'get',
        headers: { Authorization: 'Bearer ' + token }
      })
    )
  }
  //删除角色
  delRl(number) {
    if (root || auth['/roles/delete']) {
      Promise.resolve(
        $.ajax({
          url: config.Priviliege + '/roles/delete',
          type: 'post',
          headers: { Authorization: 'Bearer ' + token },
          data: {
            number
          }
        })
      ).then(res => {
        console.log(res)
        if (res.code == 200) {
          return this.getRl().then(res => {
            if (res.code == 200) {
              this.setState({
                rlTree: res.rl
              }, () => {
                message.info('删除成功')
              })
            }
          })
        } else if (res.code == 201) {
          message.info(res.msg)
        } else {
          message.info('服务器繁忙')
        }
      }).catch(err => {
        console.log(err)
        message.info('发生错误')
      })
    }
  }

  //增加角色
  addRl(number, name) {
    this.setState({
      selectedNumber: number,
      selectedName: name,
      visible: true,
      type: 2,
    })
  }

  //编辑角色
  editRl(number, name) {
    this.setState({
      selectedNumber: number,
      selectedName: name,
      visible: true,
      type: 1,
    })
  }

  //编辑角色
  editAuth(record) {
    const path = {
      pathname: '/rolesAuth',
      state: record,
    }
    hashHistory.push(path);
  }

  //模态框取消
  handleCancel() {
    this.setState({
      selectedNumber: null,
      selectedName: null,
      visible: false,
      type: 0,
    })
  }

  //查看所有权限
  allAuth(text, record) {
    const path = {
      pathname: '/rolesAllAuth',
      state: record,
    }
    hashHistory.push(path);
  }

  //模态框确认
  handleOk() {
    const form = this.props.form
    form.validateFields((err, values) => {
      const { type, selectedNumber } = this.state
      const { newName, name } = values
      console.log(values)
      if (!err) {
        return Promise.resolve().then(() => {
          if (type == 2) {//新增角色
            return $.ajax({
              url: config.Priviliege + '/roles/save',
              type: 'post',
              headers: { Authorization: 'Bearer ' + token },
              data: {
                name,
                fatherNumber: selectedNumber
              }
            })
          } else if (type == 1) { //更角色名
            return $.ajax({
              url: config.Priviliege + '/roles/update',
              type: 'post',
              headers: { Authorization: 'Bearer ' + token },
              data: {
                number: selectedNumber,
                name: newName
              }
            })
          } else {
            return {}
          }
        }).then(res => {
          console.log(res)
          if (res.code == 200) {
            return this.getRl().then(res => {
              if (res.code == 200) {
                this.setState({
                  selectedNumber: null,
                  selectedName: null,
                  visible: false,
                  type: 0,
                  rlTree: res.rl
                }, () => {
                  message.info('操作成功')
                  form.resetFields()
                })
              }
            })
          } else if (res.code == 201) {
            message.info(res.msg)
          } else {
            message.info('服务器繁忙')
          }
        }).catch(err => {
          console.log(err)
          message.info('发生错误')
        })
      }
    });
  }

  formSon(getFieldDecorator) {
    const { type, selectedName } = this.state
    if (type == 2) {
      return (
        <div style={{ paddingTop: 20 }}>
          <Input className="lasttrees" addonBefore="父级角色" value={selectedName} disabled />
          <p style={{ height: 20 }}>&nbsp;</p>
          <FormItem label='角色名称:'>
            {getFieldDecorator('name', {
              rules: [
                { max: 15, message: '长度不能超过15' },
                { required: true, message: '请输入角色名称' },
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
        </div>
      )
    } else if (type == 1) {
      return (
        <div style={{ paddingTop: 20 }}>
          <Input className="lasttrees" addonBefore="原角色名称" value={selectedName} disabled />
          <p style={{ height: 20 }}>&nbsp;</p>
          <FormItem label='新角色名称'>
            {getFieldDecorator('newName', {
              rules: [
                { max: 15, message: '长度不能超过15' },
                { required: true, message: '请输入新角色名' },
              ],
            })(
              <Input
                onChange={(e) => { e.target.value = $.trim(e.target.value).replace(' ', '') }}
              />
            )}
          </FormItem>
        </div>
      )
    }
  }
  render() {
    const columns = [
      {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        width: '45%',
      },
      {
        title: '人数',
        dataIndex: 'users.count',
        key: 'count',
        width: '15%',
        className: 'lastactiond',
      },
      {
        title: '操作',
        key: 'action',
        width: '30%',
        className: 'lastactiond',
        render: (text, record) => {
          return (
            <div>
              {(root || auth['/roles/save']) ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.addRl.bind(this, record.number, record.name)}
                >新增子集</span>
                : ''
              }
              {(root || (auth['/roles/update'] && record.level != 1)) ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.editRl.bind(this, record.number, record.name)}
                >编辑名称</span>
                : ''
              }
              {(root || (auth['/authority/roles'] && record.level != 1)) ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.editAuth.bind(this, record)}
                >设置权限</span>
                : ''
              }
              {(root || auth['/authority/getRlAllAuth']) ?
                <span
                  className='todoAction'
                  style={{ marginLeft: 10 }}
                  onClick={this.allAuth.bind(this, text, record)}
                >查看拥有权限</span>
                : ''
              }
              {((root || (auth['/roles/delete'] && record.level != 1)) && (record.number != 'rl')) ?
                <Popconfirm
                  title="确认删除吗?"
                  onConfirm={this.delRl.bind(this, record.number)}
                  okText="确认"
                  cancelText="取消"
                >
                  <span
                    className='todoAction'
                    style={{ marginLeft: 10 }}
                  >删除</span>
                </Popconfirm>
                : ''
              }
            </div>
          )
        }
      }
    ];
    const { getFieldDecorator } = this.props.form
    return (
      <div className='container' >
        <div className="box">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>权限设置</Breadcrumb.Item>
              <Breadcrumb.Item>角色管理</Breadcrumb.Item>
            </Breadcrumb>
          </div>
          {
            (root || auth['/roles/tree']) ?
              <div>
                {
                  (this.state.rlTree && this.state.rlTree.length) ? <Table
                    rowKey="number"
                    columns={columns}
                    dataSource={this.state.rlTree}
                    pagination={false}
                    bordered
                    defaultExpandedRowKeys={['rl']}
                    defaultExpandAllRows
                    className="lastsee lastseeyt"
                  // onExpandedRowsChange={this.expandedRows.bind(this)}
                  /> : ''
                }
              </div>
              :
              ''
          }
        </div>
        <Modal
          visible={this.state.visible}
          title={
            this.state.type == 1 ? '编辑角色名' : '新增角色'
          }
          width={400}
          maskClosable={false}
          onCancel={this.handleCancel.bind(this)}
          onOk={this.handleOk.bind(this)}
        >
          <Form>
            {
              this.formSon(getFieldDecorator)
            }
          </Form>
        </Modal>
      </div>
    );
  }
}
const RolesForm = Form.create()(Roles)
export default RolesForm